package com.yuan.chatrobot.controlller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.yuan.chatrobot.tulingRobot.Changeless;
import com.yuan.chatrobot.tulingRobot.Robot;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @Author 小源同学
 * @Date 2021 12 15 23 27
 * @Describe Please describe the role of this class
 **/
@WebServlet(name = "sentServlet", urlPatterns = "/sent/chat")
public class SentMassage extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String inputText = request.getParameter("inputText");
        System.out.println(inputText);
        Robot robot = new Robot();
        robot.setUrl(Changeless.URL);
        robot.setApiKey(Changeless.API_ID_2);
        robot.setUserId(Changeless.USER_ID);
        JSONArray objects = JSONUtil.parseArray(robot.Chat(inputText));
        ArrayList<JSONObject> jsonObjectArrayLists = new ArrayList<>();
        for (Object jsonObject : objects) {
            jsonObjectArrayLists.add((JSONObject) JSONUtil.parseObj(jsonObject).get("values"));
        }
        System.out.println(jsonObjectArrayLists);
        /*将list集合转成json*/
        String result = JSONUtil.parseArray(JSON.toJSONString(jsonObjectArrayLists)).toString();
        /*返回数据*/
        response.getWriter().write(result);
    }
}
